using Microsoft.AspNetCore.Mvc;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.API.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("discusscaipinxinxi")]
    public class DishDiscussionController : ControllerBase
    {
        private readonly IDishDiscussionService _discussionService;

        public DishDiscussionController(IDishDiscussionService discussionService)
        {
            _discussionService = discussionService;
        }

        /// <summary>
        /// 获取所有讨论
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<DishDiscussion>>> GetDiscussions()
        {
            var discussions = await _discussionService.GetDiscussionsAsync();
            return Ok(discussions);
        }

        /// <summary>
        /// 获取分页讨论列表
        /// </summary>
        [HttpGet("page")]
        public async Task<ActionResult<object>> GetDiscussionsPage([FromQuery] PageParams pageParams)
        {
            var discussions = await _discussionService.GetDiscussionsAsync();
            
            // 应用分页
            var pagedDiscussions = discussions
                .Skip((pageParams.PageNumber - 1) * pageParams.PageSize)
                .Take(pageParams.PageSize)
                .ToList();
                
            return Ok(PageUtils.GetPageData(pagedDiscussions, discussions.Count(), pageParams));
        }

        /// <summary>
        /// 获取讨论列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<IEnumerable<DishDiscussion>>> GetDiscussionsList(
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] long? refid = null)
        {
            var discussions = await _discussionService.GetDiscussionsAsync();
            
            // 如果指定了菜品ID,进行筛选
            if (refid.HasValue)
            {
                discussions = discussions.Where(d => d.refid == refid.Value);
            }

            // 应用分页
            var pagedDiscussions = discussions
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList();

            var total = discussions.Count();
                
            return Ok(new { 
                code = 0,
                data = new {
                    total,
                    pageSize = limit,
                    totalPage = (int)Math.Ceiling((double)total / limit),
                    currPage = page,
                    list = pagedDiscussions
                }
            });
        }

        /// <summary>
        /// 根据条件查询讨论
        /// </summary>
        [HttpPost("query")]
        public async Task<ActionResult<DishDiscussion>> QueryDiscussion([FromBody] DishDiscussion discussion)
        {
            var result = await _discussionService.GetDiscussionByQueryAsync(discussion);
            if (result == null)
            {
                return NotFound();
            }
            return Ok(result);
        }

        /// <summary>
        /// 根据条件查询讨论列表
        /// </summary>
        [HttpPost("queryList")]
        public async Task<ActionResult<IEnumerable<DishDiscussion>>> QueryDiscussionList([FromBody] DishDiscussion discussion)
        {
            var results = await _discussionService.GetDiscussionsFilteredAsync(discussion);
            return Ok(results);
        }

        /// <summary>
        /// 获取指定菜品的讨论
        /// </summary>
        [HttpGet("dish/{dishName}")]
        public async Task<ActionResult<IEnumerable<DishDiscussion>>> GetDishDiscussions(string dishName)
        {
            var discussions = await _discussionService.GetDishDiscussionsAsync(dishName);
            return Ok(discussions);
        }

        /// <summary>
        /// 获取指定ID的讨论
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<DishDiscussion>> GetDiscussion(long id)
        {
            var discussion = await _discussionService.GetDiscussionAsync(id);
            if (discussion == null)
            {
                return NotFound();
            }
            return Ok(discussion);
        }

        /// <summary>
        /// 创建讨论
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<DishDiscussion>> CreateDiscussion([FromBody] DishDiscussion discussion)
        {
            var createdDiscussion = await _discussionService.CreateDiscussionAsync(discussion);
            return CreatedAtAction(nameof(GetDiscussion), new { id = createdDiscussion.id }, createdDiscussion);
        }

        /// <summary>
        /// 保存讨论（创建或更新）
        /// </summary>
        [HttpPost("save")]
        public async Task<ActionResult<DishDiscussion>> SaveDiscussion([FromBody] DishDiscussion discussion)
        {
            DishDiscussion result;
            
            if (discussion.id > 0)
            {
                // 更新现有讨论
                result = await _discussionService.UpdateDiscussionAsync(discussion);
                if (result == null)
                {
                    return NotFound();
                }
            }
            else
            {
                // 创建新讨论
                result = await _discussionService.CreateDiscussionAsync(discussion);
            }
            
            return Ok(result);
        }

        /// <summary>
        /// 添加讨论
        /// </summary>
        [HttpPost("add")]
        public async Task<ActionResult<DishDiscussion>> AddDiscussion([FromBody] DishDiscussion discussion)
        {
            var createdDiscussion = await _discussionService.CreateDiscussionAsync(discussion);
            return Ok(createdDiscussion);
        }

        /// <summary>
        /// 回复讨论
        /// </summary>
        [HttpPut("{id}/reply")]
        public async Task<ActionResult<DishDiscussion>> ReplyDiscussion(long id, [FromBody] string reply)
        {
            var discussion = await _discussionService.ReplyDiscussionAsync(id, reply);
            if (discussion == null)
            {
                return NotFound();
            }
            return Ok(discussion);
        }

        /// <summary>
        /// 删除讨论
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteDiscussion(long id)
        {
            await _discussionService.DeleteDiscussionAsync(id);
            return NoContent();
        }
    }
}